package com.chenyue.cm.api.group;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.chenyue.cm.auth.Login;
import com.chenyue.cm.auth.LoginUser;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.vo.Page;
import com.chenyue.cm.group.domain.GroupInfo;
import com.chenyue.cm.group.domain.JdGroup;
import com.chenyue.cm.group.domain.JdGroupUser;
import com.chenyue.cm.group.domain.ViewMyGroup;
import com.chenyue.cm.group.domain.vo.MyGroupVo;
import com.chenyue.cm.group.service.GroupInfoService;
import com.chenyue.cm.group.service.JdGroupService;
import com.chenyue.cm.group.service.JdGroupUserService;
import com.chenyue.cm.group.service.ViewMyGroupService;
import com.chenyue.cm.user.domain.JdAppUser;
import com.chenyue.cm.user.domain.JdLabelSend;
import com.chenyue.cm.user.domain.vo.OwnInfoUser;
import com.chenyue.cm.user.service.JdAppUserService;
import com.chenyue.cm.user.service.JdLabelSendService;
import com.chenyue.cm.utils.DateUtils;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author libingxing
 */
@Api(tags = "我的团队")
@RestController
@RequestMapping("/api/group")
public class ApiGroupController {

    private final JdGroupService groupService;

    private final JdGroupUserService groupUserService;

    private final ViewMyGroupService viewMyGroupService;

    private final GroupInfoService groupInfoService;

    private final JdAppUserService appUserService;

    private final JdLabelSendService labelSendService;

    public ApiGroupController(JdGroupService groupService, JdGroupUserService groupUserService, ViewMyGroupService viewMyGroupService, GroupInfoService groupInfoService, JdAppUserService appUserService, JdLabelSendService labelSendService) {
        this.groupService = groupService;
        this.groupUserService = groupUserService;
        this.viewMyGroupService = viewMyGroupService;
        this.groupInfoService = groupInfoService;
        this.appUserService = appUserService;
        this.labelSendService = labelSendService;
    }

    @Login
    @PostMapping("/applyTeam")
    @ApiOperation("发起组队")
    public Success<String> applyTeam(
            @ApiIgnore @LoginUser JdAppUser user,
            @ApiParam @RequestBody JdGroup group
    ) {
        group.setLeader(Integer.valueOf(user.getId()));
        final JdGroup one = groupService.lambdaQuery().eq(JdGroup::getLeader, user.getId()).one();
        if (one != null) {
            return Success.error("每人只允许创建一支队伍");
        }
        groupService.save(group);
        return Success.success();
    }

    @Login
    @PostMapping("/enterGroup")
    @ApiOperation("申请组队")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "团队id", name = "groupId", dataType = "int", required = true),
    })
    public Success<String> enterGroup(
            @ApiIgnore @LoginUser JdAppUser user,
            Integer groupId
    ) {
        JdGroupUser one = groupUserService.lambdaQuery()
                .eq(JdGroupUser::getGroupId, groupId)
                .eq(JdGroupUser::getUserId, user.getId())
                .ne(JdGroupUser::getState, 2)
                .one();
        if (one != null) {
            return Success.error("您已经加入该队伍");
        }
        one = new JdGroupUser();
        one.setGroupId(groupId);
        one.setApplyTime(DateUtils.getToday());
        one.setState(0);
        one.setUserId(Integer.valueOf(user.getId()));
        one.setMemberName(user.getUserName());
        final boolean save = groupUserService.save(one);
        return save ? Success.success() : Success.error();
    }

    @Login
    @PostMapping("/enterCheck")
    @ApiOperation("入队审批")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "信息id", name = "id", dataType = "int", required = true),
            @ApiImplicitParam(value = "审核状态 1通过2拒绝", name = "state", dataType = "int", required = true),
            @ApiImplicitParam(value = "审核备注", name = "remark", dataType = "int", required = true),
    })
    public Success<String> enterCheck(
            Integer id, Integer state, String remark
    ) {
        if (state == 2) {
            groupUserService.delete(id);
            return Success.success();
        }
        JdGroupUser one = new JdGroupUser();
        one.setId(id);
        one.setState(state);
        one.setRemark(remark);
        final boolean save = groupUserService.updateById(one);
        return save ? Success.success() : Success.error();
    }

    @GetMapping("/groupList")
    @ApiOperation("组队大厅")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "页数", name = "page", dataType = "string", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "string", required = true),
            @ApiImplicitParam(value = "类型", name = "type", dataType = "string", required = true),
    })
    public Success<Page<List<GroupInfo>>> groupList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer rows,
            Integer type
    ) {
        final LambdaQueryChainWrapper<GroupInfo> eq = groupInfoService.lambdaQuery();
        if (type != null && type > 0) {
            eq.eq(GroupInfo::getType, type);
        }
        eq.gt(GroupInfo::getLeftCount, 0);
        final Integer total = eq.count();
        final Page<List<GroupInfo>> result = new Page<>(page, rows, total);
        final List<GroupInfo> list = eq.last(result.convertPage()).list();
        result.setContent(list);
        return Success.success(result);
    }

    @Login
    @GetMapping("/myTeam")
    @ApiOperation("我的队伍")
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "审核状态0待审核1通过2拒绝", name = "state", dataType = "string", required = true)
    })
    public Success<MyGroupVo> myTeamApply(
            @ApiIgnore @LoginUser JdAppUser user,
            Integer state
    ) {
        final JdGroup one = groupService.lambdaQuery().eq(JdGroup::getLeader, user.getId()).one();
        if (one == null) {
            return Success.error("您还没有创建过队伍");
        }
        one.setHeadImg(user.getHeadImg());
        final LambdaQueryChainWrapper<ViewMyGroup> eq = viewMyGroupService.lambdaQuery()
                .eq(ViewMyGroup::getGroupId, one.getId());
        if (state != null) {
//                0待审核 1通过 2拒绝
            eq.eq(ViewMyGroup::getState, state);
        }
        final List<ViewMyGroup> list = eq.list();
        for (ViewMyGroup viewMyGroup : list) {
            final OwnInfoUser ownInfoUser = new OwnInfoUser();
            ownInfoUser.setUser(appUserService.getById(viewMyGroup.getUserId()));
            final List<JdLabelSend> labels = labelSendService.list(new LambdaQueryWrapper<JdLabelSend>().eq(JdLabelSend::getGetUser, user.getId()));
            final List<String> labelString = labels.stream().map(JdLabelSend::getLabel).collect(Collectors.toList());
            ownInfoUser.setLabel(labelString);
            viewMyGroup.setUser(ownInfoUser);
        }
        final MyGroupVo vo = new MyGroupVo();
        vo.setList(list);
        vo.setOne(one);
        return Success.success(vo);
    }

}
